import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../utils/sputil.dart';
import '../model/_models_db.dart';

Future<List<ContactModel>> api_addressbook(context) async {
  List<ContactModel> result = List<ContactModel>.empty();

  var spu = SpUtil();

  var authorization = "Bearer ${spu.get<String>("token")}";

  try {
    final response = await http.get(
        Uri.parse('https://rtc.jxt.elef.top:8086/user/addressbook'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          "Authorization": authorization
        });

    print(response.statusCode);

    if (response.statusCode == 200) {
      //print(response.body);

      final List decodedJson =
          json.decode(new Utf8Decoder().convert(response.bodyBytes));
      result = decodedJson.map((e) => ContactModel.fromJson(e)).toList();
    } else {}
  } catch (e) {
    print(e);
  }
  return result;
}

class ContactProvider with ChangeNotifier {
  List<ContactModel> addressbooks = List<ContactModel>.empty();
  bool loading = false;

  Load(context) async {
    loading = true;
    addressbooks = await api_addressbook(context);
    loading = false;

    notifyListeners();

    return addressbooks;
  }

  getAddressBook(context, String username) async {
    if (addressbooks.isEmpty) await Load(context);

    var items = addressbooks
        .where((element) => element.Friendusername == username)
        .toList();

    if (items.isEmpty) {
      return ContactModel.empty();
    } else {
      return items[0];
    }
  }
}
